<template>
    <div :class="['card-item', flag ? 'active' : '', detail.status === '1' ? 'bg-primary' : '']" ref="taskItemRef">
        <flexbox justify="space-between">
            <HToolTip :title="detail.requestNumber">
                <span style="font-weight: 500; color: #fff" @click.stop="jumpTo" v-if="detail.status === '1'">{{ detail.requestNumber }}</span>
                <a style="font-weight: 500" @click.stop="jumpTo" v-else>{{ detail.requestNumber }}</a>
            </HToolTip>
            <HTaskType style="flex-shrink: 0" :status="detail.status" />
        </flexbox>

        <HToolTip :title="detail.requestName">
            <span class="requestName-title">
                {{ detail.requestName }}
            </span>
        </HToolTip>

        <flexbox justify="flex-end" style="margin-top: 5px" v-if="detail.status === '1'">
            <a-button size="small" @click.stop="jumpTo" v-if="detail.isRequireAnalyse === '是'">查看详情</a-button>
            <flexbox v-else>
                <a-button size="small" @click.stop="handleAccOrRefuseRequire('否')">拒绝</a-button>
                <a-button size="small" class="margin-l-8" @click.stop="handleAccOrRefuseRequire('是')">接受</a-button>
            </flexbox>
        </flexbox>
        <flexbox justify="flex-end" style="margin-top: 5px" v-else-if="['1.1'].includes(detail.status)">
            <a-button size="small" class="margin-l-8" @click.stop="handleCreateRequire">
                <PlusOutlined class="primary-color" style="font-weight: bold" />
                <span class="primary-color">新建产品需求</span>
            </a-button>
        </flexbox>
        <flexbox justify="flex-end" style="margin-top: 5px" v-else>
            <div class="pro-num-wrap">
                <div
                    style="
                        width: 16px;
                        height: 16px;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        border-radius: 50%;
                        background: rgba(4, 120, 211, 0.15);
                    "
                >
                    <span style="font-size: 12px; line-height: 12px; font-weight: 600; color: #107ed5">
                        {{ detail.pmpProductRequires ? detail.pmpProductRequires.length : 0 }}
                    </span>
                </div>
                <HToolTip title="产品需求">
                    <span class="title">产品需求</span>
                </HToolTip>
            </div>
            <a-button size="small" class="margin-l-8" @click.stop="handleCreateRequire">
                <PlusOutlined class="primary-color" style="font-weight: bold" />
                <span class="primary-color">新建产品需求</span>
            </a-button>
        </flexbox>
        <CreateStory ref="createStoryRef" :detail="detail" @success="handleSuccess" />
        <OpinionModal ref="OpinionModalRef" @success="handleOpinionSuccess" />
    </div>
</template>

<script lang="ts">
import OpinionModal from './components/OpinionModal.vue';
import store from '@/store';
import api from '@/api';
import filters from '@/utils/filter';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { useDrop } from '@/hooks/content/useDrop';
import HTaskType from './components/HTaskType.vue';
import HToolTip from '@/components/HToolTip/index.vue';
import CreateStory from '@/views/taskRequire/taskDetail/components/CreateStory.vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { defineComponent, toRefs, ref, unref, reactive, onMounted, getCurrentInstance, computed } from 'vue';
export default defineComponent({
    components: {
        HToolTip,
        HTaskType,
        PlusOutlined,
        CreateStory,
        OpinionModal
    },
    props: {
        detail: {
            type: Object,
            default: () => ({})
        }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const instance: any = getCurrentInstance();
        const router = useRouter();
        const taskItemRef = ref<any>();
        const OpinionModalRef = ref<any>();
        const createStoryRef = ref<any>();
        const state = reactive<any>({
            flag: false,
            lastenter: null
        });
        const disabled = computed(() => {
            return !store.getters.userInfo.roles.includes('产品经理');
        });

        const onDrop = (e) => {
            state.flag = false;
            if (+props.detail.status > 1) {
                handleUpdateBatch(store.getters.moveData);
            } else {
                message.error('该状态无法绑定需求');
            }
        };
        const handleUpdateBatch = async (query) => {
            if (props.detail.pmpProductRequires.find((item) => item.id === query.id)) {
                message.error('请勿重新绑定');
                return;
            }
            const { requestName, id } = props.detail;
            query = {
                ...query,
                relateRequireName: requestName,
                relateRequireId: id,
                businessChange: true
            };
            const { success, errorCode } = await api.productRequireModel.update(query);
            if (success) {
                // 重新加载当前详情
                emit('success', props.detail);
                // 如果该产品需求绑定了其他业务需求，还需要更新那个业务需求
                if (store.getters.currSelectIndex >= 0) {
                    setTimeout(() => {
                        emit('success', store.getters.taskList[store.getters.currSelectIndex]);
                    });
                }
                // 刷新业务需求，因为绑定完，待排期会变成进行中
                instance.proxy.$mitt.emit('refreshTaskList', {}, true);
            } else {
                if (errorCode === '003') {
                    return;
                }
            }
        };
        const handleShow = (ev) => {
            ev.preventDefault();
            state.lastenter = ev.target;
            state.flag = true;
        };
        const handleHide = (ev) => {
            if (state.lastenter === ev.target) {
                state.flag = false;
                ev.stopPropagation();
                ev.preventDefault();
                console.log(2);
            }
        };

        const handleCreateRequire = async (item) => {
            const { requestName, requestDesc: requireDesc, id, requestSystem, pmpProductDetailDTO, source } = props.detail;
            // 找出该系统默认的当前处理人
            const { success, moule } = await api.systemManagerModel.findManagersBySystem({
                catalogCode: pmpProductDetailDTO.catalogCode,
                position: '产品经理'
            });
            if (success) {
                // 自动填写默认值，需求类型，优先级，需求描述，所属系统，关联业务需求等
                let target = moule.find((item) => item.empId === store.getters.userInfo.employeeDTO.empId);
                target = target || moule[0];
                unref(createStoryRef).open({
                    requireName: requestName,
                    requireDesc,
                    requireType: filters.valToNameFilter('source', source) === '缺陷' ? '4' : '1',
                    level: '4',
                    agentUser: target.manager,
                    agentUserEmpId: target.empId,
                    relateRequireId: id,
                    relateRequireName: requestName,
                    requireSystem: +requestSystem,
                    devType: pmpProductDetailDTO.systemType !== '3' ? pmpProductDetailDTO.systemType : '2',
                    systemType: pmpProductDetailDTO.systemType
                });
            }
        };
        const handleSuccess = () => {
            emit('success', props.detail);
            // 刷新产品需求列表，因为新建完，未排期会增加一条数据
            instance.proxy.$mitt.emit('refreshList', {}, true);
        };
        const handleAccOrRefuseRequire = (pass) => {
            if (pass === '是') {
                handleSave({
                    pass: '是'
                });
            } else {
                OpinionModalRef.value.open();
            }
        };
        // 审核意见成功回调
        const handleOpinionSuccess = (auditOpinion) => {
            handleSave({
                auditOpinion,
                pass: '否'
            });
        };
        const getDetailData = async (id) => {
            const query = {
                id
            };
            const { moule } = await api.pmpRequestInfoModel.findById(query);
            return moule;
        };
        // 接受需求
        const handleSave = async (form = {}) => {
            const detail = await getDetailData(props.detail.id);
            const query: any = {
                ...detail,
                auditOpinion: '',
                ...form
            };
            const { success, errorMsg } = await api.pmpRequestInfoModel.save(query);
            if (success) {
                message.success('操作成功');
                if (query.pass === '否') {
                    emit('success', props.detail, 'delete');
                } else {
                    emit('success', props.detail);
                }
            } else {
                message.error(errorMsg);
            }
        };
        const jumpTo = () => {
            router.push({
                path: '/taskRequire/taskDetail',
                query: {
                    id: props.detail.id
                }
            });
        };
        onMounted(() => {
            useDrop(unref(taskItemRef), {
                onShow: handleShow,
                onHide: handleHide,
                onDrop
            });
        });
        return {
            ...toRefs(state),
            taskItemRef,
            OpinionModalRef,
            createStoryRef,
            handleCreateRequire,
            handleSuccess,
            handleSave,
            handleAccOrRefuseRequire,
            handleOpinionSuccess,
            jumpTo,
            disabled
        };
    }
});
</script>

<style scoped lang="less">
.card-item {
    height: 94px;
    width: calc(100% - 32px);
    padding: 12px 16px;
    background: #ffffff;
    box-shadow: 0px 2px 11px 0px rgba(4, 120, 211, 0.08);
    border-radius: 8px;
    margin: 0 16px 8px 16px;
    cursor: pointer;

    .requestName-title {
        color: #70798b;
    }

    .pro-num-wrap {
        display: flex;
        align-items: center;
        padding: 2px;
        border-radius: 13px;
        border: 1px solid #d9d9d9;
        font-size: 12px;
        overflow: hidden;

        .title {
            font-size: 12px;
            line-height: 12px;
            margin: 0 2px;
            color: #505a6e;
        }
    }
}
.active {
    border: 1px dashed #0176d3;
}
.bg-primary {
    background-color: @primary-color;
    .requestName-title {
        color: #fff !important;
    }
    ::v-deep(.tasktype-wrap) {
        .title {
            color: #fff !important;
        }
    }
}
</style>